const util = require('../../utils/util')
const api = require('../../utils/api')
import { getUserInfo, cancelReservation } from '../../utils/request'
Page({
  data: {
    userInfo: {},
    activeReservations: [],
    historyReservations: [],
    isLoading: false,
    currentTab: 0, // 0: 有效预约, 1: 历史预约
    remainingCancels: 10, // 默认每季度可取消10次
    showCalendar: false // 控制日历弹窗显示
  },

  onLoad: function () {
    // 检查是否已经登录
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo || !userInfo.phone) {
      wx.redirectTo({
        url: '/pages/login/login'
      })
      return
    }

    this.setData({ userInfo })

    // 开发环境提示，直接显示调试信息
    console.log('个人中心调试信息:')
    console.log('- 可查看当前预约记录和历史记录')
    console.log('- 只能在预约日前一天晚8点前取消预约')
    console.log('- 每季度只能取消预约10次')
    console.log('- 取消预约会返还相应额度')
  },

  onShow: function () {
    // 每次显示页面时刷新数据
    this.getInfo()
  },
  // 判断日期是否已过去
  isDatePassed: function (dateStr) {
    if (!dateStr) return false
    const reservationDate = new Date(dateStr)
    const today = new Date()
    
    // 设置时间为当天的开始（00:00:00）
    today.setHours(0, 0, 0, 0)
    reservationDate.setHours(0, 0, 0, 0)
    
    return reservationDate < today
  },

  // 获取状态中文显示
  getStatusText: function (status, reservationDate) {
    const statusMap = {
      active: '进行中',
      completed: '已完成',
      cancelled: '已取消',
      pending: '待处理'
    }
    
    // 如果状态是active，但日期已过去，则显示"已完成"
    if (status === 'active' && reservationDate) {
      const today = new Date()
      const resDate = new Date(reservationDate)
      
      // 设置时间为当天的开始（00:00:00）
      today.setHours(0, 0, 0, 0)
      resDate.setHours(0, 0, 0, 0)
      
      // 如果预约日期已过去（不包括今天），显示"已完成"
      if (resDate < today) {
        return '已完成'
      }
    }
    
    return statusMap[status] || status
  },

  getInfo: function () {
    getUserInfo().then((res) => {
      console.log('getUserInfo success', res)
      const userInfo = res.data
      this.setData({ userInfo })
      wx.setStorageSync('userInfo', userInfo)
      
      // 处理预约记录，添加格式化信息和状态文本
      const processedReservations = userInfo.reservations.map(item => ({
        ...item,
        statusText: this.getStatusText(item.status, item.reservation_date),
        formattedDate: util.formatDate(new Date(item.reservation_date))
      }))
      
      // 根据日期和cancelled_at字段分类预约记录
      let activeReservations = processedReservations.filter(item => {
        // 如果日期已过去或者有cancelled_at值，则为历史记录
        const isDatePassed = this.isDatePassed(item.reservation_date)
        const isCancelled = item.cancelled_at !== null && item.cancelled_at !== undefined
        
        return !isDatePassed && !isCancelled
      })
      
      // 对有效预约按照预约停车日期由近至远排序
      activeReservations.sort((a, b) => {
        const dateA = new Date(a.reservation_date)
        const dateB = new Date(b.reservation_date)
        return dateA - dateB // 升序排列，日期近的在前
      })
      
      let historyReservations = processedReservations.filter(item => {
        // 如果日期已过去或者有cancelled_at值，则为历史记录
        const isDatePassed = this.isDatePassed(item.reservation_date)
        const isCancelled = item.cancelled_at !== null && item.cancelled_at !== undefined
        
        return isDatePassed || isCancelled
      })
      
      let remainingCancels = userInfo.cancel_quota
      
      this.setData({
        activeReservations,
        historyReservations,
        remainingCancels
      })
    })
  },
  // 切换标签
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      currentTab: parseInt(tab)
    })
  },

  // 导航到预约页面
  navigateToReservation: function () {
    wx.redirectTo({
      url: '/pages/reservation/reservation'
    })
  },

  // 取消预约
  cancelResert: function (e) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认取消预约',
      content: '取消后将无法恢复，是否继续？',
      confirmColor: '#FF4D4F',
      success: (res) => {
        if (res.confirm) {
          // 用户点击确定
          cancelReservation(id).then((res) => {
            console.log('取消预约成功:', res)
            util.showToast(res.message || '取消预约成功', 'success')
            this.getInfo()
          }).catch((err) => {
            console.error('取消预约失败:', err)
            util.showToast(err.message || '取消预约失败')
          })
        }
      }
    })
  },

  // 退出登录
  handleLogout: function () {
    try {
      wx.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 移除用户信息
            wx.removeStorageSync('userInfo')
            wx.removeStorageSync('token')
            // 跳转到登录页
            wx.reLaunch({
              url: '/pages/login/login'
            })
          }
        }
      })
    } catch (error) {
      console.error('退出登录异常:', error)
      util.showToast('退出登录失败，请重试')
    }
  },

  // 显示日历视图
  showCalendarView: function () {
    this.setData({
      showCalendar: true
    })
  },

  // 隐藏日历视图
  hideCalendarView: function () {
    this.setData({
      showCalendar: false
    })
  }
})
